import { defineStore } from "pinia";
import requests from "../utils/requests";

const useGoleStore=defineStore('gole',{
	state:()=>({
		gole_name:'',
		gole_address:'',
		gole_city:'',
		traffic_lights:null,
		distance:null,
		duration:null,
		loading:1,
		rules:[],
		points_list:[],
		stop_duration:0,
		intervalId2:null,
		minutesIntervalId:null,
		show:false,
		show2:false,
	}),
	actions:{
		async locationRules(store){
			store.empty=3
			this.points_list=[]
			const res=await uni.request({
				url:'https://restapi.amap.com/v5/direction/driving',
				method:'get',
				data:{
					key:'4eac491217889d34536b62dacfa8d6f6',
					origin:`${uni.getStorageSync('longitude').toFixed(6)},${uni.getStorageSync('latitude').toFixed(6)}`,
					destination:store.gole_location,
					show_fields:"cost,tmcs,polyline",
					strategy:2
				}
			})
			const data=res.data
			store.search_list=[]
			if(data.status==="1"){
				this.rules=data.route.paths[0]
				this.traffic_lights=data.route.paths[0].cost.traffic_lights
				this.distance=data.route.paths[0].distance
				this.duration=data.route.paths[0].cost.duration
				this.gole_address=store.gole_address
				this.gole_name=store.gole_name
				this.gole_city=store.gole_city
				uni.setStorageSync('gole_latitude',Number(store.gole_location.split(',')[1]))
				uni.setStorageSync('gole_longitude',Number(store.gole_location.split(',')[0]))
				for (let item in this.rules.steps){
					const pairs = this.rules.steps[item].polyline.split(';')
					pairs.forEach(pair => {
					    const [longitude, latitude] = pair.split(',');
					    this.points_list.push({
					        latitude: Number(latitude),
					        longitude: Number(longitude)
					    });
					});
				}
			}else{
				console.log(`规划失败：${data.errdetail}`)
			}
		},
		async refleshLocationRules(store){
			this.rules=[]
			const res=await uni.request({
				url:'https://restapi.amap.com/v5/direction/driving',
				method:'get',
				data:{
					key:'4eac491217889d34536b62dacfa8d6f6',
					origin:`${uni.getStorageSync('selfLongitude').toFixed(6)},${uni.getStorageSync('selfLatitude').toFixed(6)}`,
					destination:store.gole_location,
					show_fields:"cost,tmcs,polyline",
					strategy:2
				}
			})
			const data=res.data
			if(data.status==="1"){
				this.rules=data.route.paths[0]
			}
		},
		async caluate(){
			const faraway_distance=Number((this.rules.distance/1000).toFixed(1))
			if (faraway_distance===0){
				this.faraway_distance=`还有${this.rules.distance}米`
			}else{
				this.faraway_distance=`还有${faraway_distance}公里`
			}
			const hours=Math.floor(this.rules.cost.duration / 3600)
			const remainingSeconds =this.rules.cost.duration % 3600
			const seconds=Math.floor(remainingSeconds / 60)
			if(hours===0){
				this.faraway_time=`预计${seconds}分钟到达`
			}else{
				this.faraway_time=`预计${hours}小时${seconds}分钟到达`
			}
			await uni.setStorageSync('time_distance',`${this.faraway_distance},${this.faraway_time}`)
		},
		addmarker(homeStore,marker,polyline,marker_dict,gole_location_marker){
			homeStore.markers=[]
			homeStore.polyline_list=[]
			marker[1]['latitude']=uni.getStorageSync('gole_latitude')
			marker[1]['longitude']=uni.getStorageSync('gole_longitude')
			polyline[0]['points']=this.points_list
			homeStore.empty=2
			homeStore.markers=marker
			homeStore.polyline_list=polyline
			homeStore.latitude=uni.getStorageSync('gole_latitude')
			homeStore.longitude=uni.getStorageSync('gole_longitude')
		},
		async changemarker(homeStore,marker_dict2){
			await homeStore.markers.pop()
			marker_dict2.callout.content=uni.getStorageSync('time_distance')
			marker_dict2.latitude=uni.getStorageSync('selfLatitude')
			marker_dict2.longitude=uni.getStorageSync('selfLongitude')
			await homeStore.markers.push(marker_dict2)
			homeStore.latitude=uni.getStorageSync('selfLatitude')
			homeStore.longitude=uni.getStorageSync('selfLongitude')
		},
		async total(homeStore,marker,polyline,marker_dict,gole_location_marker){
			await this.locationRules(homeStore)
			await this.caluate()
			await this.addmarker(homeStore,marker,polyline,marker_dict,gole_location_marker)
		},
		async refleshGole(homeStore,marker_dict2){
			await homeStore.refleshSelfLocation()
			await this.refleshLocationRules(homeStore)
			await this.caluate()
			await this.changemarker(homeStore,marker_dict2)
		},
		startTime(homeStore,marker_dict2){
		  if (this.intervalId2 === null) {
		    this.intervalId2 = setInterval(() => {
		      this.stop_duration++;
			  console.log(this.stop_duration)
		    }, 1000);
		  }
		  if (this.minutesIntervalId === null) {
		    this.minutesIntervalId = setInterval(() => {
				this.refleshGole(homeStore,marker_dict2)
		    }, 60000);
		  }
		},
		stopTime(){
		  if (this.intervalId2 !== null) {
		    clearInterval(this.intervalId2);
			this.intervalId2= null;
		  }
		  if (this.minutesIntervalId !== null) {
		    clearInterval(this.minutesIntervalId);
		  	this.minutesIntervalId = null;
		  }
		},
		startGole(homeStore,marker_dict,marker_dict2){
			this.loading=2
			this.show=true
			this.startTime(homeStore,marker_dict2)
			homeStore.markers.push(marker_dict)
			homeStore.markers[3].callout.content=uni.getStorageSync('time_distance')
			homeStore.latitude=uni.getStorageSync('latitude')
			homeStore.longitude=uni.getStorageSync('longitude')
		},
		stopClose(homestore,marker){
			this.loading=1
			this.show=false
			this.show2=false
			this.stop_duration=0
			homestore.empty=0
			homestore.markers=[]
			homestore.markers=marker
			homestore.polyline_list=[]
		},
		async confirm(homestore){
			this.stopTime()
			const spend_time= await this.stop_duration_time()
			this.loading=3
			this.show2=true
			homestore.markers.pop()
			uni.removeStorageSync('gole_latitude')
			uni.removeStorageSync('gole_longitude')
			await this.addHistory(spend_time)
		},
		isModelShow(homeStore){
			uni.showModal({
				title:'结束定位',
				content:'确定要结束定位到达医疗站点吗',
				showCancel:true,
				success: (res) => {
					if (res.confirm) {
						this.confirm(homeStore)
					}
				},
				fail: () => {
					console.log('打开弹窗失败')
				}
			})
		},
		stop_duration_time(){
			const hours=Math.floor(this.stop_duration / 3600)
			const remainingSeconds =this.stop_duration % 3600
			const seconds=Math.floor(remainingSeconds / 60)
			if(hours===0){
				return `${seconds}分钟`
			}else{
				return `${hours}小时${seconds}分钟`
			}
		},
		async addHistory(spend_time){
			const res=await requests({
				url:'/base/locationHistory/',
				method:'post',
				data:{
					username:uni.getStorageSync('username'),
					address:`${this.gole_name}(${this.gole_address})`,
					spend_time:spend_time
				}
			})
			if(res.code===200){
				console.log('添加历史记录成功')
			}else{
				console.log('添加历史记录失败')
			}
		},
		quitStart(homestore,marker){
			homestore.markers=[]
			homestore.markers=marker
			homestore.polyline_list=[]
			homestore.latitude=uni.getStorageSync('latitude')
			homestore.longitude=uni.getStorageSync('longitude')
			homestore.empty=0
		}
	},
})
export default useGoleStore;